﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace SmartSpace.Core
{
    public static class EntityRepository
    {
        /// <summary>
        /// 保存实体
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool Save<TEntity>(TEntity entity, DbContext context) where TEntity : class, IKeyEntity
        {
            Logger.Debug("EntityRepository", "开始保存IGuidKeyEntity,实体类型[{0}],Id[{1}]", typeof(TEntity).FullName, entity.Id);
            bool result = true;

            if (entity.Id == Guid.Empty)
            {
                Logger.Debug("EntityRepository", "Id为Guid.Empty，无法执行保存操作,实体类型[{0}],Id[{1}]", typeof(TEntity).FullName, entity.Id);
                result = false;
            }
            else
            {
                if (context.Set<TEntity>().Where(p => p.Id == entity.Id)
                    .Select(p => p.Id).SingleOrDefault() == default(Guid))
                {
                    context.Set<TEntity>().Add(entity);
                    Logger.Debug("EntityRepository", "实体不存在于Context中，执行添加操作,实体类型[{0}],Id[{1}]", typeof(TEntity).FullName, entity.Id);
                }
                else
                {
                    context.Entry(entity).State = EntityState.Modified;
                    Logger.Debug("EntityRepository", "实体存在于Context中，执行修改操作,实体类型[{0}],Id[{1}]", typeof(TEntity).FullName, entity.Id);
                }
            }
            return result;
        }

        public static bool Delete(IKeyEntity entity, DbContext context)
        {
            if (context.Set<IKeyEntity>().Where(p => p.Id == entity.Id)
                .Select(p => p.Id).SingleOrDefault() == default(Guid))
            {
                return true;
            }
            else
            {
                context.Entry(entity).State = EntityState.Deleted;
                return true;
            }
        }

        public static void Delete<TEntity>(Guid entityId, DbContext context) where TEntity : class, IKeyEntity
        {
            IKeyEntity entity = context.Set<TEntity>().Where(p => p.Id == entityId).SingleOrDefault();
            if (entity != null)
            {
                context.Entry(entity).State = EntityState.Deleted;
            }
        }

        public static IKeyEntity Get(Guid entityId, DbContext context)
        {
            return context.Set<IKeyEntity>().Where(p => p.Id == entityId).Single();
        }

        public static bool Commit(DbContext context)
        {
            Logger.Debug("EntityRepository", "开始执行提交");
            bool result = false;
            try
            {
                if (context.SaveChanges() > 0)
                {
                    result = true;
                    Logger.Debug("EntityRepository", "执行提交成功");
                }
                else
                {
                    Logger.Debug("EntityRepository", "执行提交失败，没有影响的结果数");
                }
            }
            catch(Exception ex)
            {
                Logger.Error("EntityRepository", "执行提交失败，发生异常", ex);
            }
            return result;
        }

        /// <summary>
        /// 删除继承了接口ICodeEntity的实体对象，
        /// 在这个操作之后需要调用Commit方法
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool SaveCodeEntity<TEntity>(TEntity entity, DbContext context) where TEntity : class, ICodeEntity
        {
            if (context.Set<TEntity>().Where(p => p.Id == entity.Id && p.Code == entity.Code)
                .Select(p => p.Id).SingleOrDefault() != default(Guid))
            {
                context.Entry(entity).State = EntityState.Modified;
            }
            else if (context.Set<TEntity>().Where(p=> p.Code == entity.Code)
                .Select(p => p.Id).SingleOrDefault() != default(Guid))
            {
                return false;
            }
            else
            {
                context.Set<TEntity>().Add(entity);
            }
            return true;
        }

        public static bool DeleteCodeEntity<TEntity>(TEntity entity, DbContext context) where TEntity : class, ICodeEntity
        {
            if (context.Set<TEntity>().Where(p => p.Id == entity.Id && p.Code == entity.Code)
                .Select(p => p.Id).SingleOrDefault() == default(Guid))
            {
                return true;
            }
            else
            {
                context.Entry(entity).State = EntityState.Deleted;
                return true;
            }
        }

        public static TEntity GetCodeEntity<TEntity>(string code, DbContext context) where TEntity : class, ICodeEntity
        {
            return context.Set<TEntity>().Where(p => p.Code == code).SingleOrDefault();
        }

        public static TEntity GetCodeEntity<TEntity>(Guid id, DbContext context) where TEntity : class, ICodeEntity
        {
            return context.Set<TEntity>().Where(p => p.Id == id).SingleOrDefault();
        }

        public static bool DeleteCodeEntity<TEntity>(string code, DbContext context) where TEntity : class, ICodeEntity
        {
            TEntity entity = context.Set<TEntity>().Where(p => p.Code == code).SingleOrDefault();
            if (entity == null)
            {
                return true;
            }
            else
            {
                context.Entry(entity).State = EntityState.Deleted;
            }
            return true;
        }

        public static bool DeleteCodeEntity<TEntity>(Guid id, DbContext context) where TEntity : class, ICodeEntity
        {
            TEntity entity = context.Set<TEntity>().Where(p => p.Id == id).SingleOrDefault();
            if (entity == null)
            {
                return true;
            }
            else
            {
                context.Entry(entity).State = EntityState.Deleted;
            }
            return true;
        }
    }
}
